import { useDark, useToggle } from "@vueuse/core";
import { PerspectiveCamera, Vector3 } from "three";
import { onUnmounted, ref, unref } from "vue";

export const useAddEvent = (camera: PerspectiveCamera) => {
  const leftPress = ref<boolean>();
  const left=ref<boolean>(false)
  const right=ref<boolean>(false)
  const front=ref<boolean>(false)
  const back=ref<boolean>(false)
  const isCustomLook=ref<boolean>(false)

  const initMouse = () => {
    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("mousedown", handleMouseDown);
    window.addEventListener("mouseup", handleMouseUp);
  };

  const initKeyDown=()=>{
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);
  }
  // 键盘按下
const handleKeyDown = (event) => {

    console.log(event.keyCode);
    switch (event.keyCode) {
      case 65: // a
        left.value = true;
        break;
      case 68: // d
        right.value = true;
        break;
      case 83: // s
        back.value = true;
        break;
      case 87: // w
        front.value = true;
        break;
    }
  };
  // 键盘谈起
  const handleKeyUp = (event) => {
    console.log(event.keyCode);
    switch (event.keyCode) {
      case 65: // a
        left.value = false;
        break;
      case 68: // d
        right.value = false;
        break;
      case 83: // s
        back.value = false;
        break;
      case 87: // w
        front.value = false;
        break;
    }
  };

  const handleMouseDown = (event: any) => {
    event.preventDefault();
    leftPress.value = true;
  };
  const handleMouseUp = (event: any) => {
    console.log('鼠标按下')
    isCustomLook.value=true
    event.preventDefault();
    leftPress.value = false;
  };

  const handleMouseMove = (event: any) => {
    event.preventDefault();

    if (leftPress.value) {

      camera.rotateOnWorldAxis(
        new Vector3(0, 1, 0),
        event.movementX / 500
      );
      camera.rotateOnAxis(
        new Vector3(1, 0, 0),
        event.movementY / 500
      );
    }
  };

  onUnmounted(() => {
    window.removeEventListener("mousemove", handleMouseMove);
    window.removeEventListener("mousedown", handleMouseDown);
    window.removeEventListener("mouseup", handleMouseUp);
    window.removeEventListener("keydown", handleKeyDown);
    window.removeEventListener("keyup", handleKeyUp);
  });
  return {
    initMouse,
    initKeyDown,
    left, right, front, back,
    isCustomLook
  };
};
